from fastapi import APIRouter
from pydantic import BaseModel

from business.base.AjaxJson import AjaxJson
from utils.MySqlUtil import MySqlUtil

router = APIRouter(
    prefix="/order",
    tags=["order"],
    responses={404: {"description": "Not found"}},
)


class PageObj(BaseModel):
    pageNumber: int = None
    pageSize: int = None


@router.post("/findOrderList")
async def findOrderList(page: PageObj):
    pageNumber = 1 if page.pageNumber == 0 else page.pageNumber
    pageSize = page.pageSize
    j = AjaxJson()
    j.code = 'failure'
    j.msg = '获取分页数据失败'
    sql = 'SELECT * FROM confirm_order limit %s,%s'
    db = MySqlUtil()
    data = db.query(sql, ((pageNumber - 1) * pageSize, pageSize))
    count = db.get_count('SELECT count(1) FROM confirm_order', None)
    result = {
        "orderList": data,
        "count": count
    }
    j.data = result
    j.code = 'success'
    j.msg = '获取分页数据成功'
    return j


@router.get("/getOrder")
async def getOrder(order_id: str):
    j = AjaxJson()
    j.code = 'failure'
    j.msg = '获取订单信息失败'
    order_sql = 'SELECT * FROM confirm_order t WHERE t.id = %s'
    db = MySqlUtil()
    order_result = db.query(order_sql, order_id)
    if len(order_result) > 0:
        item_sql = 'SELECT b.specification ,b.nature,b.goods_name as goodsName,b.price FROM confirm_order_item a,' \
                   'goods b WHERE a.goods_id = b.id AND a.order_id = %s '
        item_result = db.query(item_sql, order_id)
        j.code = 'success'
        j.msg = '获取订单信息成功'
        j.data = item_result
    return j
